package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * SqlSession接口及其实现类用于封装CRUD方法
 *
 * @author YiYa
 * @since 2020-11-08 上午 10:26
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        List<Object> query = simpleExecutor.query(configuration, mapperStatement, params);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw  new RuntimeException("返回为空或返回结果过多!");
        }
    }

    @Override
    public Integer insertOne(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        Integer insert = simpleExecutor.insert(configuration, mapperStatement, params);
        return insert;
    }

    @Override
    public Integer updateOne(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        Integer update = simpleExecutor.update(configuration, mapperStatement, params);
        return update;
    }

    @Override
    public Integer deleteOne(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        Integer delete = simpleExecutor.delete(configuration, mapperStatement, params);
        return delete;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 底层都还是去执行JDBC代码 //根据不同情况，来调用selectList或者selectOne
                // 准备参数 1：statementId :sql语句的唯一标识：namespace.id= 接口全限定名.方法名
                // 方法名：findAll
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                String sql = configuration.getMapperStatementMap().get(statementId).getSql();

                // 准备参数2：params:args
                // 获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                // 判断是否进行了 泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    List<Object> objects = selectList(statementId, args);
                    return objects;
                }

                // 判断增删改
                if (sql.contains("insert")) {
                    return insertOne(statementId, args);
                } else if (sql.contains("update")) {
                    return updateOne(statementId, args);
                } else if (sql.contains("delete")) {
                    return deleteOne(statementId, args);
                } else {
                    return selectOne(statementId, args);
                }
            }
        });
        return (T) proxyInstance;
    }
}
